package com.cms.common.aop.permission;


import com.cms.common.context.ApplicationContextProvider;
import com.cms.common.model.services.PermissionService;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Aspect
@Component
@Slf4j
public class PermissionCheckAspect {

    @Around("@annotation(com.cms.common.aop.permission.PermissionCheck)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        Signature signature = pjp.getSignature();
        Class<?> clazz = pjp.getTarget().getClass();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method targetMethod = methodSignature.getMethod();
        PermissionService permissionService = ApplicationContextProvider.getBean(PermissionService.class);
        boolean checkPermission = permissionService.checkPermission(targetMethod, clazz);
        if (checkPermission) {
            return pjp.proceed();
        }
        return null;
    }
}
